<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { showToast } from 'vant'
import TreeDisplay from '../components/TreeDisplay.vue'
import { useFormStore } from '../stores/formStore';
import { onActivated, onDeactivated } from 'vue'
import { getEnterpriseById, updateEnterprise } from '../api/enterprise';
import UserSteps from '../components/UserSteps.vue';
onActivated(() => {
  // console.log('组件被激活')
})

onDeactivated(() => {
  // console.log('组件被缓存')
})

// const props = defineProps<{ msg?: string }>()
// 添加组件 name 选项
defineOptions({
  name: 'FormPage'
})

const formStore = useFormStore()

// 访问store 数据
const departmentList = computed(() => formStore.generatedData)
const parentNodeShow = ref(false)
// 添加一个状态来标识是否在编辑模式
const isEditMode = ref(false)
// 添加一个变量来保存正在编辑的节点ID
const editingNodeId = ref<number | null>(null)

const form = reactive({
  name: '',
  manager: '',
  gender: '',
  parentNode: '',
  staffCount: '',
  childrenNodes: []
})
// 生成的数据列表
const generatedData = ref<any[]>([])
// 初始上级部门选项
const initialParentNodeOptions = [
  { text: '无上级部门/顶级部门', value: '无上级部门/顶级部门' }
]
// 动态计算上级部门选项（包括初始选项和已生成的部门）
const parentNodeOptions = computed(() => {
  const options = [...initialParentNodeOptions]

  // 递归函数收集所有部门名称
  const collectNodeNames = (nodes: any[]) => {
    nodes.forEach(data => {
      // 编辑模式下，排除正在编辑的节点，避免选择自己作为父节点
      if (isEditMode.value && editingNodeId.value === data.id) {
        return
      }

      options.push({
        text: data.name,
        value: data.name
      })

      // 递归处理子部门
      if (data.childrenNodes && data.childrenNodes.length > 0) {
        collectNodeNames(data.childrenNodes)
      }
    })
  }

  // 收集已生成的部门及其子部门
  collectNodeNames(generatedData.value)

  return options
})

// 递归构造树形结构部门数据
const generateTree = (parentNodeName: string, nodeData: any) => {
  // 如果父部门名称为空或"无上级部门/顶级部门"，则添加到根部门
  if (!parentNodeName || parentNodeName === '无上级部门/顶级部门') {
    generatedData.value.push(nodeData);
    return;
  }

  // 递归查找并添加子部门
  const findAndAddChild = (nodes: any[], parentName: string, childNode: any): boolean => {
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      // 找到匹配的父部门
      if (node.name === parentName) {
        node.childrenNodes.push(childNode);
        return true;
      }
      // 递归查找子部门
      if (node.childrenNodes && node.childrenNodes.length > 0) {
        if (findAndAddChild(node.childrenNodes, parentName, childNode)) {
          return true;
        }
      }
    }
    return false;
  };

  // 在已生成的数据中查找父部门并添加子部门
  findAndAddChild(generatedData.value, parentNodeName, nodeData);
};

// 递归查找并更新节点
const findAndUpdateNode = (nodes: any[], targetId: number, updatedData: any): boolean => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.id === targetId) {
      // 保留原有的 childrenNodes
      const childrenNodes = node.childrenNodes || [];
      // 更新节点数据
      Object.assign(node, updatedData);
      // 恢复 childrenNodes
      node.childrenNodes = childrenNodes;
      return true;
    }
    // 递归查找子节点
    if (node.childrenNodes && node.childrenNodes.length > 0) {
      if (findAndUpdateNode(node.childrenNodes, targetId, updatedData)) {
        return true;
      }
    }
  }
  return false;
};

// 递归查找并删除节点
const findAndDeleteNode = (nodes: any[], targetId: number): boolean => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.id === targetId) {
      // 找到目标节点，从数组中移除
      nodes.splice(i, 1);
      return true;
    }
    // 递归查找子节点
    if (node.childrenNodes && node.childrenNodes.length > 0) {
      if (findAndDeleteNode(node.childrenNodes, targetId)) {
        return true;
      }
    }
  }
  return false;
};

// 递归查找节点
const findNode = (nodes: any[], targetId: number): any => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.id === targetId) {
      return node;
    }
    // 递归查找子节点
    if (node.childrenNodes && node.childrenNodes.length > 0) {
      const found = findNode(node.childrenNodes, targetId);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 处理编辑事件
const handleEdit = (node: any) => {
  // 设置为编辑模式
  isEditMode.value = true;
  editingNodeId.value = node.id;

  // 填充表单数据
  form.name = node.name;
  form.manager = node.manager;
  form.gender = node.gender;
  form.parentNode = node.parentNode;
  form.staffCount = node.staffCount;

  // 使用 nextTick 确保 DOM 更新后再滚动到表单顶部
  nextTick(() => {
    // 方法1: 滚动到页面顶部
    // window.scrollTo({ top: 0, behavior: 'smooth' });  //不生效不知道为啥

    // 方法2: 如果上面的方法不工作，可以尝试滚动到具体元素
    // const formElement = document.querySelector('.form-page');
    // if (formElement) {
    //   formElement.scrollIntoView({ behavior: 'smooth' });
    // }

    // 方法3: 如果有特定的表单容器，可以直接滚动到该容器
    const formContainer = document.querySelector('.form-container');
    if (formContainer) {
      formContainer.scrollIntoView({ behavior: 'smooth' });
    }
  });
};

// 处理删除事件
const handleDelete = (nodeId: number) => {
  // 查找要删除的节点
  const nodeToDelete = findNode(generatedData.value, nodeId);
  if (nodeToDelete) {
    // 确认删除，提示中包含部门名称
    const confirmDelete = window.confirm(`确定要删除部门/岗位【${nodeToDelete.name}】吗？`);
    if (confirmDelete) {
      findAndDeleteNode(generatedData.value, nodeId);
      showToast('删除成功');
    }
  }
}
// 重置表单
const resetForm = () => {
  form.name = '';
  form.manager = '';
  form.gender = '';
  form.parentNode = '';
  form.staffCount = '';
  isEditMode.value = false;
  editingNodeId.value = null;
};

// 提交表单并生成数据
const onSubmit = () => {
  if (!form.name) {
    showToast('请输入名称')
    return
  }
  if (!form.manager) {
    showToast('请输入负责人')
    return
  }
  if (!form.gender) {
    showToast('请选择负责人性别')
    return
  }
  if (!form.parentNode) {
    showToast('请选择上级部门')
    return
  }
  if (!form.staffCount) {
    showToast('请输入编制人数')
    return
  }

  // 生成数据对象
  const newData = {
    id: isEditMode.value ? editingNodeId.value : Date.now(),
    name: form.name,
    manager: form.manager,
    gender: form.gender,
    parentNode: parentNodeOptions.value.find(item => item.value === form.parentNode)?.text || '无上级部门/顶级部门',
    staffCount: form.staffCount,
    childrenNodes: []

  }

  if (isEditMode.value && editingNodeId.value) {
    // 更新现有节点
    const oldNode = findNode(generatedData.value, editingNodeId.value);
    if (oldNode && oldNode.parentNode !== form.parentNode) {
      // 上级部门发生变更，需要调整层级结构
      // 1. 先删除原节点
      findAndDeleteNode(generatedData.value, editingNodeId.value);
      // 2. 再重新添加到新的父节点下
      generateTree(form.parentNode, newData);
    } else {
      // 上级部门未变更，只更新节点信息
      findAndUpdateNode(generatedData.value, editingNodeId.value, newData);
    }
    showToast('数据更新成功');
  } else {
    // 添加新节点到数据列表
    generateTree(form.parentNode, newData);
    showToast('数据生成成功');
  }
  formStore.updateForm(generatedData.value)
  // 重置表单
  console.log('数据列表', departmentList.value)
  resetForm();
}
// 添加保存组织架构的处理函数
const saveOrganizationStructure = async () => {
  // 将当前生成的数据保存到 store 中
  let user = JSON.parse(localStorage.getItem('user')!)
  const response: any = await getEnterpriseById(user.enterpriseId).catch(err => {
    console.log("获取失败", err);
  });
  if (response && response.data && response.code === 200) {
    const data = response.data;
    data.orgJson = JSON.stringify(generatedData.value)
    updateEnterprise(data).catch((err) => {
      showToast('组织架构保存失败');
      console.log("保存失败", err);

    })
  }

  // 例如发送到后端服务器等
  console.log('保存的组织架构数据:', generatedData.value);
  showToast('组织架构保存成功');

};

onMounted(() => {
  // 获取当前用户信息
  let user = JSON.parse(localStorage.getItem('user')!)
  // 获取当前用户的企业信息
  getEnterpriseById(user.enterpriseId).then((res: any) => {
    if (res.code === 200) {
      const data = res.data
      if (data.orgJson) {
        // 解析组织架构数据
        generatedData.value = JSON.parse(data.orgJson)
      }
    }
  })
})

</script>

<template>
  <div class="form-page">
    <UserSteps :currentStep="1" style="margin-bottom: 2vh;" />

    <van-form @submit="onSubmit" class="form-container">
      <van-cell-group inset>
        <van-field v-model="form.name" label="名称" placeholder="请输入部门/岗位名称" label-align="left" />

        <van-field v-model="form.manager" label="负责人" placeholder="请输入负责人姓名" label-align="left" />

        <van-cell title="负责人性别" title-align="left" value-align="left">
          <template #right-icon>
            <van-radio-group v-model="form.gender" direction="horizontal">
              <van-radio name="男">男</van-radio>
              <van-radio name="女">女</van-radio>
            </van-radio-group>
          </template>
        </van-cell>

        <van-field v-model="form.parentNode" label="上级部门" placeholder="请选择上级部门" readonly @click="parentNodeShow = true"
          label-align="left" />

        <van-field v-model="form.staffCount" label="编制人数" placeholder="请输入编制人数" type="number" label-align="left" />
      </van-cell-group>

      <div class="form-actions">
        <van-button round block type="primary" native-type="submit">
          {{ isEditMode ? '更新部门/岗位' : '新增部门/岗位' }}
        </van-button>

        <van-button v-if="isEditMode" round block type="default" @click="resetForm" style="margin-top: 10px;">
          取消编辑
        </van-button>
      </div>

    </van-form>
    <!-- 显示生成的数据 -->
    <!-- 显示生成的数据 -->
    <div v-if="generatedData.length > 0" class="data-display" style="margin-bottom: 15px;">
      <van-divider>已生成的数据</van-divider>
      <van-cell-group inset>
        <TreeDisplay :nodes="generatedData" @edit="handleEdit" @delete="handleDelete" />
      </van-cell-group>
    </div>
    <van-popup v-model:show="parentNodeShow" position="bottom">
      <van-picker :columns="parentNodeOptions"
        @confirm="({ selectedValues }) => { form.parentNode = selectedValues[0]; parentNodeShow = false }"
        @cancel="parentNodeShow = false" />
    </van-popup>
    <!-- 添加保存组织架构按钮 -->
    <div v-if="generatedData.length > 0" class="save-actions"
      style="width: 85vw; margin: 20px auto 0;margin-bottom: 65px;">
      <van-button round block type="primary" @click="saveOrganizationStructure">
        保存组织架构
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.form-page {
  padding: 5px;
  padding: 5px;
  min-height: 50vh;
  display: flex;
  flex-direction: column;
  font-size: 16px;
  margin-top: 16px;
  margin-bottom: auto;
}

.form-actions {
  width: 75%;
  margin-top: 20px;
}

.data-display {
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: auto;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px;

}

:deep(.van-radio-group) {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 20px;
}

:deep(.van-cell__title) {
  text-align: left;
  font-size: 16px;
}

:deep(.van-cell__label) {
  width: 90vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.van-cell-group--inset) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 85vw;
}

:deep(.van-collapse-item__title) {
  font-weight: bold;
  font-size: large;
}
</style>